package com.lion.seaman.worker.jobs;

import com.lion.seaman.common.Constants;
import com.lion.seaman.common.LoadJs;
import com.lion.seaman.common.tools.StringTools;
import com.lion.seaman.common.type.JobFlowStatus;
import com.lion.seaman.common.type.JobStatus;
import com.lion.seaman.orm.bin.SpringContext;
import com.lion.seaman.orm.bin.SystemConfig;
import com.lion.seaman.worker.flows.JobFlow;
import com.lion.seaman.worker.flows.JobTree;
import com.lion.seaman.worker.jobs.logic.IJobLogic;
import org.apache.log4j.Logger;

import java.util.HashMap;
import java.util.Map;

public class SimpleJob implements Runnable {
    private Logger log = Logger.getLogger(SimpleJob.class);
    protected String jobId;
    protected JobTree jobTree;
    protected IJobLogic jobLogic;
    protected Map<String, Object> jobData = new HashMap<>();
    protected JobStatus jobStatus = JobStatus.REDAY;
    protected SystemConfig systemConfig;

    public SimpleJob(String jobId, String scriptPath) {
        systemConfig = SpringContext.getBean(SystemConfig.class);
        this.jobId = jobId;
        try {
            String resourcesPath = systemConfig.get("sys.resources.path", SimpleJob.class.getResource("/").getPath());
            jobLogic = LoadJs.load(resourcesPath, scriptPath);
            jobData.put(Constants.DEFAULT_JOB_ID_KEY, jobId);
            jobLogic.init(jobData);
            this.jobTree = jobLogic.createTree();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        jobStatus = JobStatus.RUNNING;
        log.info(StringTools.format("job {0} is running", jobId));
        JobStatus tmpStatus = JobStatus.SUCCESS;
        while (jobTree.hasNext()) {
            JobFlow jobFlow = jobTree.next().getJobFlow();
            jobFlow.run();
            if (jobFlow.getJobFlowStatus() == JobFlowStatus.ERROR) {
                tmpStatus = JobStatus.ERROR;
                break;
            }
        }
        this.jobStatus = tmpStatus;
        log.info(StringTools.format("job {0} is complete,job status:{1}", jobId, this.jobStatus));
        jobLogic.complete(jobData);

    }

    public void putAllData(Map<String, Object> jobData) {
        this.jobData.putAll(jobData);
    }

}
